import sys
from PySide6.QtWidgets import (
    QApplication,
    QWidget,
    QVBoxLayout,
    QHBoxLayout,
    QPushButton,
    QTableWidget,
    QTableWidgetItem,
)
import pyqtgraph as pg
import numpy as np


class DataVisualizer(QWidget):
    """数据可视化器"""

    def __init__(self):
        super().__init__()
        self.init_ui()
        # 初始化数据
        self.data = [
            {"name": "Point1", "value": [1, 3]},
            {"name": "Point2", "value": [2, 8]},
            {"name": "Point3", "value": [1, 4]},
            {"name": "Point4", "value": [4, 10]},
        ]
        # 变换状态
        self.transform_state = {
            "xy_swap": False,  # XY轴是否互换
            "origin_x": 0,  # 原点X偏移
            "origin_y": 0,  # 原点Y偏移
        }
        self.selected_point = None
        self.update_plot()
        self.update_table()

    def init_ui(self):
        """初始化UI"""
        # 主布局
        layout = QHBoxLayout(self)

        # 左侧控制面板
        left_panel = QWidget()
        left_layout = QVBoxLayout(left_panel)

        # 添加控制按钮
        swap_btn = QPushButton("XY轴互换")
        swap_btn.clicked.connect(self.on_swap_xy)
        left_layout.addWidget(swap_btn)

        # 添加数据表格
        self.table = QTableWidget()
        self.table.setColumnCount(3)
        self.table.setHorizontalHeaderLabels(["序号", "名称", "坐标"])
        left_layout.addWidget(self.table)

        # 右侧图形面板
        self.plot_widget = pg.PlotWidget()
        self.plot_widget.showGrid(x=True, y=True)

        # 添加到主布局
        layout.addWidget(left_panel)
        layout.addWidget(self.plot_widget)

        # 设置窗口属性
        self.setWindowTitle("数据可视化示例")
        self.resize(800, 600)

    def update_plot(self):
        """更新图形显示"""
        self.plot_widget.clear()

        # 提取数据
        x = np.array([item["value"][0] for item in self.data])
        y = np.array([item["value"][1] for item in self.data])

        # 应用变换
        if self.transform_state["xy_swap"]:
            x, y = y, x

        # 创建散点图
        self.scatter = pg.ScatterPlotItem(
            x=x + self.transform_state["origin_x"],
            y=y + self.transform_state["origin_y"],
            symbol="o",
            size=10,
            pen=pg.mkPen(None),
            brush=pg.mkBrush(0, 0, 255, 200),
            hoverable=True,
            hoverBrush=pg.mkBrush(255, 0, 0, 200),
            hoverSize=15,
        )

        self.scatter.sigClicked.connect(self.on_point_clicked)
        self.plot_widget.addItem(self.scatter)

        # 更新坐标轴标签
        if self.transform_state["xy_swap"]:
            self.plot_widget.setLabel("left", "X轴")
            self.plot_widget.setLabel("bottom", "Y轴")
        else:
            self.plot_widget.setLabel("left", "Y轴")
            self.plot_widget.setLabel("bottom", "X轴")

    def update_table(self):
        """更新数据表格"""
        self.table.setRowCount(len(self.data))
        for i, item in enumerate(self.data):
            self.table.setItem(i, 0, QTableWidgetItem(str(i + 1)))
            self.table.setItem(i, 1, QTableWidgetItem(item["name"]))
            self.table.setItem(i, 2, QTableWidgetItem(str(item["value"])))
        self.table.resizeColumnsToContents()

    def on_swap_xy(self):
        """处理XY轴互换"""
        self.transform_state["xy_swap"] = not self.transform_state["xy_swap"]
        self.update_plot()

    def on_point_clicked(self, plot, points):
        """处理点击事件"""
        if self.selected_point is not None:
            self.selected_point.setBrush(pg.mkBrush(0, 0, 255, 200))
            self.selected_point.setSize(10)

        if points:
            point = points[0]
            point.setBrush(pg.mkBrush(255, 0, 0, 200))
            point.setSize(15)
            self.selected_point = point

            # 高亮对应的表格行
            self.table.selectRow(point.index())


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = DataVisualizer()
    window.show()
    sys.exit(app.exec())